package com.isman.placeslist.adapter;

import net.londatiga.android.ActionItem;
import net.londatiga.android.QuickAction;
import net.londatiga.android.QuickAction.OnActionItemClickListener;

import com.isman.placeslist.PageUser;
import com.isman.placeslist.R;
import com.isman.placeslist.database.PeopleContent;
import com.isman.placeslist.ws.AsyncRunnerHeadler;
import com.isman.placeslist.ws.ServiceProvider;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.view.View.OnCreateContextMenuListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.TextView;

public class PeopleAdapter extends CursorAdapter {
	private static final int VIEW_TYPE_GROUP_START = 0;
	private static final int VIEW_TYPE_GROUP_CONT = 1;
	private static final int VIEW_TYPE_COUNT = 2;

	private static final int ID_CALL = 1;
	private static final int ID_MESSAGE = 2;
	private static final int ID_EMAIL = 3;

	private Button vbtnCancelRequest;
	private Button vbtnAcceptFriend;
	private Button vbtnUnaccepFriend;
	private Button vbtnBlockFriend;

	public PeopleAdapter(Activity mActivity, Cursor cursor) {
		super(mActivity, cursor);
		this.mActivity = mActivity;

		mColUID = cursor.getColumnIndexOrThrow(PeopleContent.UID);
		mColUEmail = cursor.getColumnIndexOrThrow(PeopleContent.UEMAIL);
		mColUName = cursor.getColumnIndexOrThrow(PeopleContent.UNAME);
		mColUTel = cursor.getColumnIndexOrThrow(PeopleContent.UEMAIL);
		mColUPic = cursor.getColumnIndexOrThrow(PeopleContent.UPICTURE);
		mColPStatus = cursor.getColumnIndexOrThrow(PeopleContent.PSTATUS);
	}

	@Override
	public int getViewTypeCount() {
		return VIEW_TYPE_COUNT;
	}

	@Override
	public int getItemViewType(int position) {
		if (position == 0) {
			return VIEW_TYPE_GROUP_START;
		}

		Cursor cursor = getCursor();
		cursor.moveToPosition(position);
		boolean newGroup = isNewGroup(cursor, position);

		if (newGroup) {
			return VIEW_TYPE_GROUP_START;
		} else {
			return VIEW_TYPE_GROUP_CONT;
		}
	}

	@Override
	public View newView(Context context, Cursor cursor, ViewGroup parent) {
		int position = cursor.getPosition();
		int nViewType;

		if (position == 0) {
			// Group header for position 0
			nViewType = VIEW_TYPE_GROUP_START;
		} else {
			// For other positions, decide based on data
			boolean newGroup = isNewGroup(cursor, position);

			if (newGroup) {
				nViewType = VIEW_TYPE_GROUP_START;
			} else {
				nViewType = VIEW_TYPE_GROUP_CONT;
			}
		}

		View v;
		if (nViewType == VIEW_TYPE_GROUP_START) {
			v = LayoutInflater.from(mActivity).inflate(
					R.layout.inc_item_people_with_header, parent, false);

		} else {
			v = LayoutInflater.from(mActivity).inflate(
					R.layout.inc_item_people, parent, false);
		}
		return v;
	}

	@Override
	public void bindView(View view, Context context, final Cursor cursor) {
		ImageView img = (ImageView) view
				.findViewById(R.id.img_item_people_profile);
		img.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				final QuickAction mQuickAction = new QuickAction(mActivity);
				if (!cursor.getString(mColUTel).equals("")) {
					mQuickAction.addActionItem(new ActionItem(mActivity,
							ID_CALL, R.drawable.ic_menu_call));
					mQuickAction.addActionItem(new ActionItem(mActivity,
							ID_MESSAGE, R.drawable.ic_menu_sms));
				}
				if (!cursor.getString(mColUEmail).equals("")) {
					mQuickAction.addActionItem(new ActionItem(mActivity,
							ID_EMAIL, R.drawable.ic_menu_mail));
				}
				mQuickAction
						.setOnActionItemClickListener(new ItemEvent(cursor));
				mQuickAction.show(v);
			}
		});
		final long userId = cursor.getLong(mColUID);
		// Image
		byte[] data = cursor.getBlob(mColUPic);
		if (data != null) {
			Bitmap mp = BitmapFactory.decodeByteArray(data, 0, data.length);
			img.setImageBitmap(mp);
			img.setScaleType(ScaleType.FIT_XY);
		}

		view.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
			@Override
			public void onCreateContextMenu(ContextMenu arg0, View arg1,
					ContextMenuInfo arg2) {
				final CharSequence[] items = { "Block", "Remove" };

				AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
				builder.setTitle("Pick a color");
				builder.setItems(items, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int item) {
						switch (item) {
						case 0:
							mBlockFriend(userId);
							break;
						case 1:
							mDeleteFriend(userId);
							break;
						}
					}
				});
				AlertDialog alert = builder.create();
				alert.show();	
			}
		});

		vbtnCancelRequest = (Button) view
				.findViewById(R.id.btn_uDetail_cancelRequest);
		vbtnAcceptFriend = (Button) view
				.findViewById(R.id.btn_uDetail_acceptfriend);
		vbtnUnaccepFriend = (Button) view
				.findViewById(R.id.btn_uDetail_unacceptfriend);
		vbtnBlockFriend = (Button) view
				.findViewById(R.id.btn_uDetail_blockfriend);

		initData(cursor.getInt(mColPStatus));

		vbtnAcceptFriend.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				mAccepRequest(userId);
			}
		});
		vbtnCancelRequest.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				mCancelRequest(userId);
			}
		});
		vbtnUnaccepFriend.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				mUnaccepRequest(userId);
			}
		});
		vbtnBlockFriend.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				mBlockFriend(userId);
			}
		});

		TextView tv;
		tv = (TextView) view.findViewById(R.id.lbl_item_people_headname);
		if (tv != null) {
			tv.setText(cursor.getString(mColUName).charAt(0) + "");
		}

		tv = (TextView) view.findViewById(R.id.lbl_item_people_name);
		tv.setText(cursor.getString(mColUName));

		tv.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(mActivity, PageUser.class);
				intent.putExtra(PageUser.USER_ID, userId);
				mActivity.startActivity(intent);
			}
		});
	}

	private boolean isNewGroup(Cursor cursor, int position) {
		char nWhenThis = cursor.getString(mColUName).charAt(0);
		cursor.moveToPosition(position - 1);
		char nWhenPrev = cursor.getString(mColUName).charAt(0);
		cursor.moveToPosition(position);
		if (nWhenPrev != nWhenThis) {
			return true;
		}
		return false;
	}

	private void initData(int statusId) {
		switch (statusId) {
		case 0:
			vbtnCancelRequest.setVisibility(View.GONE);
			vbtnAcceptFriend.setVisibility(View.GONE);
			vbtnUnaccepFriend.setVisibility(View.GONE);
			vbtnBlockFriend.setVisibility(View.GONE);
			break;
		case 1:
			vbtnCancelRequest.setVisibility(View.GONE);
			vbtnAcceptFriend.setVisibility(View.VISIBLE);
			vbtnUnaccepFriend.setVisibility(View.VISIBLE);
			vbtnBlockFriend.setVisibility(View.VISIBLE);
			break;
		case 2:
			vbtnCancelRequest.setVisibility(View.VISIBLE);
			vbtnAcceptFriend.setVisibility(View.GONE);
			vbtnUnaccepFriend.setVisibility(View.GONE);
			vbtnBlockFriend.setVisibility(View.GONE);
			break;
		case 3:
			vbtnCancelRequest.setVisibility(View.GONE);
			vbtnAcceptFriend.setVisibility(View.GONE);
			vbtnUnaccepFriend.setVisibility(View.GONE);
			vbtnBlockFriend.setVisibility(View.GONE);
			break;
		}
	}

	private void mDeleteFriend(final long mFriendUserId) {
		ServiceProvider provider = new ServiceProvider(mActivity);
		provider.unFriend(mFriendUserId,new AsyncRunnerHeadler() {
			@Override
			public void onError(int statusCode, String json) {
				mActivity.runOnUiThread(new Runnable() {
					@Override
					public void run() {
						ContentResolver mContentResolver = mActivity
								.getContentResolver();
						mContentResolver
								.delete(PeopleContent.CONTENT_URI,
										PeopleContent.UID + " = "
												+ mFriendUserId, null);
					}
				});
			}
			
			@Override
			public void onConnectingError(String message) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onComplete(String json) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onAuthenticate(String json) {
				// TODO Auto-generated method stub
				
			}
		});
	}

	private void mCancelRequest(final long mFriendUserId) {
		ServiceProvider provider = new ServiceProvider(mActivity);
		provider.cancelRequestFriend(mFriendUserId, new AsyncRunnerHeadler() {
			@Override
			public void onComplete(String json) {
				mActivity.runOnUiThread(new Runnable() {
					@Override
					public void run() {

						ContentResolver mContentResolver = mActivity
								.getContentResolver();
						mContentResolver
								.delete(PeopleContent.CONTENT_URI,
										PeopleContent.UID + " = "
												+ mFriendUserId, null);
					}
				});
			}

			@Override
			public void onAuthenticate(String json) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onError(int statusCode, String json) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onConnectingError(String message) {
				// TODO Auto-generated method stub

			}
		});
	}

	private void mAccepRequest(final long mFriendUserId) {
		ServiceProvider provider = new ServiceProvider(mActivity);
		provider.acceptFriend(mFriendUserId, new AsyncRunnerHeadler() {
			@Override
			public void onComplete(String json) {
				mActivity.runOnUiThread(new Runnable() {
					@Override
					public void run() {
						ContentResolver mContentResolver = mActivity
								.getContentResolver();
						ContentValues values = new ContentValues();
						values.put(PeopleContent.PSTATUS, 3);
						mContentResolver.update(PeopleContent.CONTENT_URI,
								values, PeopleContent.UID + " = "
										+ mFriendUserId, null);
					}
				});
			}

			@Override
			public void onAuthenticate(String json) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onError(int statusCode, String json) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onConnectingError(String message) {
				// TODO Auto-generated method stub

			}
		});
	}

	private void mUnaccepRequest(final long mFriendUserId) {
		ServiceProvider provider = new ServiceProvider(mActivity);
		provider.unAcceptFriend(mFriendUserId, new AsyncRunnerHeadler() {
			@Override
			public void onComplete(String json) {
				mActivity.runOnUiThread(new Runnable() {
					@Override
					public void run() {
						ContentResolver mContentResolver = mActivity
								.getContentResolver();
						mContentResolver
								.delete(PeopleContent.CONTENT_URI,
										PeopleContent.UID + " = "
												+ mFriendUserId, null);
					}
				});
			}

			@Override
			public void onAuthenticate(String json) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onError(int statusCode, String json) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onConnectingError(String message) {
				// TODO Auto-generated method stub

			}
		});
	}

	private void mBlockFriend(final long mFriendUserId) {
		ServiceProvider provider = new ServiceProvider(mActivity);
		provider.blockFriend(mFriendUserId, new AsyncRunnerHeadler() {
			@Override
			public void onComplete(String json) {
				mActivity.runOnUiThread(new Runnable() {
					@Override
					public void run() {
						ContentResolver mContentResolver = mActivity
								.getContentResolver();
						ContentValues values = new ContentValues();
						values.put(PeopleContent.PSTATUS, 3);
						mContentResolver.update(PeopleContent.CONTENT_URI,
								values, PeopleContent.UID + " = "
										+ mFriendUserId, null);
					}
				});
			}

			@Override
			public void onAuthenticate(String json) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onError(int statusCode, String json) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onConnectingError(String message) {
				// TODO Auto-generated method stub

			}
		});
	}

	public class ItemEvent implements OnActionItemClickListener {
		private Cursor mCursor;

		public ItemEvent(Cursor mCursor) {
			this.mCursor = mCursor;
		}

		@Override
		public void onItemClick(QuickAction quickAction, int pos, int actionId) {
			Intent intent;

			if (actionId == ID_CALL) {
				intent = new Intent(Intent.ACTION_CALL);
				intent.setData(Uri.parse("tel:" + mCursor.getString(mColUTel)));
				mActivity.startActivity(Intent.createChooser(intent,
						"Select Call application."));

			} else if (actionId == ID_MESSAGE) {
				intent = new Intent(Intent.ACTION_VIEW, Uri.parse("smsto:"
						+ mCursor.getString(mColUTel)));
				intent.putExtra("sms_body", "");
				mActivity.startActivity(Intent.createChooser(intent,
						"Select SMS application."));

			} else if (actionId == ID_EMAIL) {
				intent = new Intent(Intent.ACTION_SEND);
				// i.setType("text/plain"); //use this line for testing in the
				// emulator
				intent.setType("message/rfc822");
				intent.putExtra(Intent.EXTRA_EMAIL,
						new String[] { mCursor.getString(mColUEmail) });
				// intent.putExtra(Intent.EXTRA_SUBJECT,"subject goes here");
				// intent.putExtra(Intent.EXTRA_TEXT,"body goes here");
				mActivity.startActivity(Intent.createChooser(intent,
						"Select email application."));
			}
		}

	}

	private Activity mActivity;
	private int mColUID;
	private int mColUEmail;
	private int mColUName;
	private int mColUTel;
	private int mColUPic;

	// private int mColPID;
	private int mColPStatus;
}